package com.youaishujuhui.devops.web.util;

import org.apache.commons.codec.digest.DigestUtils;

import java.util.*;

/**
 * 类说明
 *
 * @author 陈沈钿
 * @create 2018-09-05 11:02
 **/
public class SignTool {

    public static List<String> dictionary(Map<String, String> map) {
        List<String> list = new ArrayList<String>();
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            list.add(entry.getKey());
        }
        Collections.sort(list);
        return list;
    }

    /*****
     *
     *  1）有中文的字段值，一定要使用 UrlEncode(value, "UTF-8") 编码
     2）将除 sign 外的所有参数按照字典升序排列
     3）将第2步排序好的参数(key=value)用&拼接起来
     4）将第3步生成的字符串 + "&${appKey}", 得到源串
     5）md5签名第4步的源串
     *
     * @param params
     * @param secretKey
     * @return
     */
    public static String sign(Map<String, String> params, String secretKey) {

        StringBuilder stringBuilder = appendParams(params);
        stringBuilder.append(secretKey);
        return DigestUtils.md5Hex(stringBuilder.toString().getBytes());
    }

    public static StringBuilder appendParams(Map<String, String> params) {
        List<String> dictionary = dictionary(params);
        StringBuilder stringBuilder = new StringBuilder();
        for(String k : dictionary){
            stringBuilder.append(k).append("=").append(params.get(k)).append("&");
        }
        return stringBuilder;
    }
}
